package id;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class Ider {

    BufferedImage lower;
    BufferedImage upper;
    BufferedImage input;
    BufferedImage result;

    Color back = new Color(240,240,240);
    
    public Ider() {
	result = new BufferedImage( 2000 , 400 , BufferedImage.TYPE_INT_ARGB );
    }

    public void loadLetters() {
	try {
	    lower = ImageIO.read( new File( "lowercase.png" ) );
	    upper = ImageIO.read( new File( "uppercase.png" ) );
	    input = ImageIO.read( new File( "coded.png" ) );
	} catch ( IOException e ) {
	    e.printStackTrace();
	}
    }

    private int compareRGB( int rgb1 , int rgb2 ) {
	Color c1 = new Color( rgb1 );
	Color c2 = new Color( rgb2 );

	int diff = Math.abs( c1.getRed() - c2.getRed() ) + Math.abs( c1.getGreen() - c2.getGreen() ) + Math.abs( c1.getBlue() - c2.getBlue() );
	return diff;
    }

    private void check( BufferedImage chars , int x , int sens , int lineheight , int cx , int cy ) {
	int total = 0;
	for ( int x2 = 0; x2 < chars.getWidth(); x2++ ) {
	    if ( compareRGB( chars.getRGB( x2 , lineheight ) , input.getRGB( x , 0 ) ) < sens ) {

		int i = 0;
		while ( (x2 + i) < chars.getWidth() && (x + i) < input.getWidth() && compareRGB( chars.getRGB( x2 + i , 8 ) , input.getRGB( x + i , 0 ) ) < sens ) {
		    i++;
		    if ( i > 3 && chars.getRGB( x2 + i , 8 ) == back.getRGB() )
			break;
		}

		if ( i > 3 ) {
		    System.out.println( "hit! @ " + x + "  " + i + " . " + total );

		    BufferedImage temp = lower.getSubimage( x2 , 0 , cx , cy );
		    result.getGraphics().drawImage( temp , x , 10 + total * 20 , null );
		    i = 0;
		    x2 += 2;
		    total++;
		}
	    }
	}
    }

    public void run() {
	int sens = 1;
	for ( int x = 0; x < input.getWidth(); x++ ) {
	    check( lower , x , sens , 10 , 6 , 14 );
	    // check( upper, x, sens, 8,6,8);
	}
	try {
	    BufferedImage temp2 = input.getSubimage( 0 , 0 , input.getWidth() , 8 );
	    result.getGraphics().drawImage( temp2 , 0 , 0 , null );
	    System.out.println( "writing file!" );
	    ImageIO.write( result , "png" , new File( "Output.png" ) );
	} catch ( IOException e ) {
	    e.printStackTrace();
	}
    }
}
